#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("服务端");
    // 创建实例
    server = new QTcpServer(this);
    // 连接信号槽
    connect(server, &QTcpServer::newConnection, this, &Widget::processConnection);
    // 绑定监听
    bool ret = server->listen(QHostAddress::Any, 8000);
    if (!ret)
    {
        QMessageBox::critical(this, "启动失败", server->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    // 通过tcpserver拿到socket对象，通过socket和客户端通信
    QTcpSocket* socket = server->nextPendingConnection();
    QString log = "[" + socket->peerAddress().toString() + ":" +
                  QString::number(socket->peerPort()) + "] 客户端连接";
    // 通过信号槽，处理客户端请求
    connect(socket, &QTcpSocket::readyRead, this, [=]{
        // 读取数据，返回QByteArray，赋值转换QString
        QString request = socket->readAll();
        // 处理响应
        const QString& response = process(request);
        // 响应写回客户端
        socket->write(response.toUtf8());
        // 内容记录界面
        QString log = "[" + socket->peerAddress().toString() + ":" +
                      QString::number(socket->peerPort()) + "]" + request;
        ui->listWidget->addItem(log);
    });
    // 信号槽处理断开连接
    connect(socket, &QTcpSocket::disconnected, this, [=]{
        // 断开日志
        QString log = "[" + socket->peerAddress().toString() + ":" +
                      QString::number(socket->peerPort()) + "] 客户端断开";
        ui->listWidget->addItem(log);
        // 释放资源
        socket->deleteLater();
    });
}

QString Widget::process(const QString& request)
{
    return request;
}

